/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_httpd.htm
 *
 * Zhiqim Httpd is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.httpd.model;

import org.zhiqim.httpd.HttpContext;
import org.zhiqim.httpd.HttpHeader;
import org.zhiqim.kernel.model.codes.MD5;
import org.zhiqim.kernel.util.Validates;

/**
 * HTTP协议中的域名、端口和上下文环境值
 *
 * @version v1.0.0 @author zouzhigang 2021-3-28 新建与整理
 */
public class HttpDomainPortPath
{
    private String domain;
    private int port;
    private String path;
    
    /*********************************************************************************************/
    //从协议中解析域名、端口和上下文环境值，以及生成idMark和cookiePrefix
    /*********************************************************************************************/
    
    /** 从HTTP协议头中读出 */
    public HttpDomainPortPath parse(HttpHeader header)
    {
        HttpContext context = header.getContext();
        domain = context.getCookieDomain();
        if (Validates.isEmpty(domain))
            domain = header.getHostOnly();
        
        port = context.getCookiePort();
        if (port == 0)
            port = header.getPort();
        
        path = context.getCookiePath();
        if (Validates.isEmpty(path))
            path = context.getContextPath();
        
        return this;
    }

    /** 生成会话ID标记 */
    public String buildSessionIdMark()
    {
        return MD5.encodeUTF8(new StringBuilder(domain).append(":").append(port).append(path).toString()).substring(8, 24);
    }
    
    /** 生成Cookie前缀 */
    public String buildCookiePrefix(boolean isCookieForce)
    {
        return isCookieForce?new StringBuilder(domain).append(":").append(port).append(path).append(".").toString():null;
    }
    
    /*********************************************************************************************/
    //获取属性
    /*********************************************************************************************/
    
    public String getDomain()
    {
        return domain;
    }

    public int getPort()
    {
        return port;
    }

    public String getPath()
    {
        return path;
    }
}
